<template>
  <b-row cols="10">
    <b-col cols="3">
      <b-list-group>
        <b-list-group-item
          href="#"
          v-for="conversation in conversations"
          :key="conversation.id"
          :active="activeConversationId === conversation.id"
          @click="chooseConversation(conversation)"
        >
          {{ conversation.meta.sender.name }}
          <b-badge v-if="activeConversationId === conversation.id" variant="light">{{ conversation.unreadCount }}</b-badge>
          <b-badge v-else variant="primary">{{ conversation.unreadCount }}</b-badge>
        </b-list-group-item>
      </b-list-group>
    </b-col>
    <b-col cols="7">
      <chat-head></chat-head>
      <chat-body :grouped-messages="messages"></chat-body>
    </b-col>
  </b-row>
</template>

<script>
import ChatHead from '@/components/ChatHead'
import ChatBody from '@/components/ChatBody'
import { mapActions, mapGetters } from 'vuex'

export default {
  components: {
    ChatHead,
    ChatBody
  },
  computed: {
    ...mapGetters({
      conversations: 'conversation/getConversations'
    }),
    messages () {
      const [chat] = this.conversations.filter(
        c => c.id === this.activeConversationId
      )
      if (chat) {
        return chat.messages
      } else {
        return []
      }
    }
  },
  data () {
    return {
      activeConversationId: ''
    }
  },
  async created () {
    const inboxId = '60c1f433-f28f-2ff9-70d8-3a08aca539f0'
    const status = ''
    const assigneeType = 'all'
    const page = 1

    await this.getConversations({
      inboxId,
      status,
      assigneeType,
      page
    })

    if (this.conversations && this.conversations.length > 0) {
      this.activeConversationId = this.conversations[0].id
    }

    this.updateCurrentConversationId(this.activeConversationId)
  },
  methods: {
    ...mapActions('conversation', [
      'getConversations',
      'setActiveChat',
      'updateCurrentConversationId'
    ]),

    chooseConversation (conversation) {
      this.activeConversationId = conversation.id
      this.setActiveChat(conversation)
      this.updateCurrentConversationId(this.activeConversationId)
    }
  }
}
</script>

<style>
.question-previews .list-group-item {
  cursor: pointer;
}
</style>
